//
//  shallow_deep_copy.cpp
//  learnC++
//
//  Created by liuzhibing on 2018/6/7.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#include "shallow_deep_copy.hpp"


MyString3::MyString3(const MyString3 &source){
    std::cout<< "copy construct";
    m_length = source.m_length;
    
    // m_data is a pointer, so we need to deep copy it if it is non-null
    if (source.m_data)
    {
        // allocate memory for our copy
        m_data = new char[m_length];
        
        // do the copy
        for (int i=0; i < m_length; ++i)
            m_data[i] = source.m_data[i];
    }else{
        m_data = nullptr;
    }
    
}

MyString3& MyString3::operator=(const MyString3 &source){
    std::cout<< "operator=";
    // check for self-assignment
    if (this == &source)
        return *this;
    
    // first we need to deallocate any value that this string is holding!
    delete[] m_data;
    
    // because m_length is not a pointer, we can shallow copy it
    m_length = source.m_length;
    
    // m_data is a pointer, so we need to deep copy it if it is non-null
    if (source.m_data)
    {
        // allocate memory for our copy
        m_data = new char[m_length];
        
        // do the copy
        for (int i=0; i < m_length; ++i)
            m_data[i] = source.m_data[i];
    }
    else
        m_data = 0;
    
    return *this;
}

